#define _CRT_SECURE_NO_WARNINGS

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* mergeKLists(struct ListNode** lists, int listsSize) {
    if (listsSize == 0)
        return NULL;
    if (listsSize == 1)
        return lists[0];

    struct ListNode* newHead = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* cur = newHead;

    int mid = listsSize / 2;
    struct ListNode* cur1 = mergeKLists(lists, mid);
    struct ListNode* cur2 = mergeKLists(lists + mid, listsSize - mid);

    while (cur1 && cur2)
    {
        if (cur1->val < cur2->val)
        {
            cur->next = cur1;
            cur1 = cur1->next;
        }
        else
        {
            cur->next = cur2;
            cur2 = cur2->next;
        }
        cur = cur->next;
    }

    cur->next = cur1 == NULL ? cur2 : cur1;

    struct ListNode* ret = newHead->next;
    free(newHead);
    return ret;

}